﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;
using JM.JCY.Common;
using System.Globalization;
using JM.JCY.Proxy;
using JM.JCY.BusinessEntity;
using System.Data;
using Microsoft.SharePoint;

namespace JM.JCY.SharePointComponent.News.HomeNews
{
    public partial class HomeNewsUserControl : UserControl, ICallbackEventHandler
    {
        private int currentPageIndex;
        private string lastIndex = "1";
        private string ImageUrlForPlayPauseBtn = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string callbackReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveCallback", "context", false);
                string callbackScript = string.Format("function CallServer(arg,context){{ {0}  }}", callbackReference);
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServer", callbackScript, true);
            }
        }

        public string PartSubString(string fieldName, string fieldValue)
        {
            string returnVal = fieldValue;
            if (fieldName == "Subject" && fieldValue.Length > 50)
                returnVal = fieldValue.Substring(0, 50);
            else if (fieldName == "Summary" && fieldValue.Length > 100)
                returnVal = fieldValue.Substring(0, 100);
            return returnVal;
        }

        protected void BindList(int pageIndex)
        {
            using (NewsProxy proxy = new NewsProxy())
            {
                NewsDataSet.T_NewsDataTable NewsDT = proxy.GetNewsForHome("News", Int32.Parse(JCYConstant.DisplayCount));
                lastIndex = NewsDT.Rows.Count.ToString();
                DataTable dt = JM.JCY.Common.JCYUtility.GetNewDataTable(NewsDT, string.Format("Seq={0}", pageIndex), "");

                foreach (DataRow dr in dt.Rows)
                {
                    dr["ImageUrl"] = SPContext.Current.Site.ServerRelativeUrl + dr["ImageUrl"];
                    dt.AcceptChanges();
                }

                this.dlNews.DataSource = dt;
                dlNews.DataBind();
            }

        }

        public string GetCallbackResult()
        {
            //Return the rebind datalist's content
            return RenderControl(dlNews);
        }

        //Realize ICallbackEventHandler member RaiseCallbackEvent
        public void RaiseCallbackEvent(string eventArgument)
        {
            if (eventArgument.IndexOf('|') >= 0)
            {
                string[] split = eventArgument.Split('|');
                currentPageIndex = Convert.ToInt32(split[0]);
                ImageUrlForPlayPauseBtn = split[1];
            }
            BindList(currentPageIndex);

        }

        private string RenderControl(Control control)
        {
            StringWriter writer1 = new StringWriter(CultureInfo.InvariantCulture);
            HtmlTextWriter writer2 = new HtmlTextWriter(writer1);

            control.RenderControl(writer2);
            writer2.Flush();
            writer2.Close();

            return writer1.ToString() + "|@|@|@" + lastIndex;
        }

        protected void dlNews_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            // load date format
            Label lblEffDate = (Label)e.Item.FindControl("lblEffDate");

            string dateString = lblEffDate.Text;
            DateTime dateTime = DateTime.Parse(ConvertDateFormat(dateString));
            lblEffDate.Text = dateTime.ToString(JCYConstant.Date_Format_CN);

            ImageButton imgback = (ImageButton)e.Item.FindControl("imgback");
            ImageButton imgplaypause = (ImageButton)e.Item.FindControl("imgplaypause");
            ImageButton imgforward = (ImageButton)e.Item.FindControl("imgforward");
            if (ImageUrlForPlayPauseBtn != "")
                imgplaypause.ImageUrl = ImageUrlForPlayPauseBtn;    //Set display Play or Pause image for play/pause button

            imgback.Attributes.Add("onclick", "backClick();return false;");
            imgplaypause.Attributes.Add("onclick", "playpauseClick(this);return false;");
            imgforward.Attributes.Add("onclick", "forwardClick();return false;");
        }

        private string ConvertDateFormat(string date)
        {
            var str = date.Split('/');
            return str[1].ToString() + "/" + str[0].ToString() + "/" + str[2].ToString();
        }
    }
}
